
import sys

try:
    # Python 3.x
    from configparser import SafeConfigParser
    from xmlrpc.server import SimpleXMLRPCServer 
except:
    # Python 2.x
    from ConfigParser import SafeConfigParser
    from SimpleXMLRPCServer import SimpleXMLRPCServer 

try:
    # PySide version
    #raise # force use of PyQt until PySide UILoader sub-classing works again (see http://bugs.pyside.org/show_bug.cgi?id=1060)
    from PySide import QtCore, QtGui
    from PySide.QtUiTools import QUiLoader
except:
    # PyQt version
    from PyQt4 import QtCore, QtGui, uic
    QtCore.Signal = QtCore.pyqtSignal
    QtCore.Slot = QtCore.pyqtSlot
    
    
UI_FILE = "WebViewer.ui"
CFG_FILE = "WebViewer.cfg"


class MyMainWindow(QtGui.QMainWindow):
    
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        
        # the GUI is loaded here
        self.ui = None
        
        if 'QUiLoader' in globals():
            # PySide
            self.ui = loadUi(UI_FILE, self)
        if 'uic' in globals():
            # PyQt
            ui_class, widget_class = uic.loadUiType(UI_FILE) 
            self.ui = ui_class() 
            self.ui.setupUi(self)
            
        # configuration parser to keep track of state
        self.config = SafeConfigParser({'URI':'http://www.google.com'})
        self.config.read(CFG_FILE)

        # show main UI
        self.show()
        
        url = QtCore.QUrl("http://www.google.com")
        self.ui.webView.load(url)             

    def closeEvent(self, event):
        #print("closeEvent")
        
        # save configuration to file
        fp = open(CFG_FILE, 'wt')
        self.config.write(fp)
        fp.close()
        print("closed?: ", fp.closed)
        
        # pass to the parent to close properly
        super(MyMainWindow, self).closeEvent(event)
        
    # Menu items
    
    @QtCore.Slot()
    def on_actionExit_triggered(self):
        print("on_actionExit_triggered")
        self.close()
        
    @QtCore.Slot()
    def on_actionAbout_triggered(self):
        print("on_actionAbout_triggered")
        text = "Luna Web Viewer to test web services:\n"
        if 'QUiLoader' in globals():
            import PySide
            text += "  PySide v" + PySide.__version__ + "\n  compiled with Qt v" + QtCore.__version__ + "\n  running with Qt v" + QtCore.qVersion()
        else:
            text += "  PyQt4 v" + QtCore.PYQT_VERSION_STR
        QtGui.QMessageBox.about(self, "About Me", text)
        
                
class MyApp(QtGui.QApplication):
    
    def __init__(self):
        super(MyApp, self).__init__(sys.argv)
        self.frame = MyMainWindow()

        # Setup a timer for idle processing
        timer = QtCore.QTimer(self)
        timer.timeout.connect(self.onIdle)
        timer.start()

    def onIdle(self):
        #print("onIdle")
        pass
        
    def main(self):
        app.exec_()
        
        
# special stub for PySide version to do the same as the PyQt4 framework
if 'QUiLoader' in globals():
    class MyQUiLoader(QUiLoader):
        def __init__(self, baseinstance):
            super(MyQUiLoader, self).__init__()
            self.baseinstance = baseinstance
    
        def createWidget(self, className, parent=None, name=""):
            widget = super(MyQUiLoader, self).createWidget(className, parent, name)
            if parent is None:
                return self.baseinstance
            else:
                setattr(self.baseinstance, name, widget)
                return widget
    
    def loadUi(uifile, baseinstance=None):
        loader = MyQUiLoader(baseinstance)
        ui = loader.load(uifile)
        QtCore.QMetaObject.connectSlotsByName(ui)
        return ui


if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description='Luna Web Viewer')
    #parser.add_argument('--camera', action='store', help='specify which camera to use. zero-based.')
    
    args = parser.parse_args()
    print(args)
    
#    if args.camera:
#        camera_index = int(args.camera)
        
    app = MyApp()
    sys.exit(app.main())
